package com.aiyige.page.my.settings.acount;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventSetWalletPwdSuccess;
import com.aiyige.model.SmsCode;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.page.login.callbacks.ITimerCallBack;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.VerifyCodeManager;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.vondear.rxtools.RxTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 修改钱包密码验证
 * xiachao
 */
@Route(path = ARouterConfig.ChangeWalletPasswordVerifyCodePage)
public class ChangeWalletPasswordVerifyCodePage extends BaseActivity implements ITimerCallBack {
    public static final String TAG = ChangeWalletPasswordVerifyCodePage.class.getSimpleName();

    @BindView(R.id.tv_current_phone)
    TextView tvCurrentPhone;

    @BindView(R.id.et_verify_code)
    EditText etVerifyCode;

    @BindView(R.id.btn_send_verify_code)
    Button btnSendVerifyCode;

    boolean isPasswordVisible = false;


    @Autowired
    public String userId;

    SmsCode smsCode;

    boolean sending = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_change_wallet_password_verify);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        etVerifyCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
//                checkPassword(s.toString());
            }
        });

        etVerifyCode.setImeOptions(EditorInfo.IME_ACTION_DONE);
        etVerifyCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    doNext();
                    return true;
                }
                return false;
            }
        });
        tvCurrentPhone.setText(getResources().getString(R.string.the_current_account_binding_mobile_phone_number_value, getPhone()));
//        checkPassword(null);
        btnSendVerifyCode.setEnabled(true);
        setAutoRegisterEventBus(true);
        VerifyCodeManager.getInstance().addLoginCallBack(this);
    }

    private String getPhone() {
        return AccountUtil.getMobile();
    }

//    private void checkPassword(String password) {
//        btnSendVerifyCode.setEnabled(!isEmpty(password) && password.length() == 6);
//    }

    private void doNext() {
        if (smsCode == null) {
            ToastX.show(getResources().getString(R.string.please_input_verify_code));
            return;
        }
        if (smsCode != null && !TextUtils.isEmpty(getPhone()) &&
                !TextUtils.isEmpty(smsCode.getCode()) &&
                smsCode.getMobile().equals(getPhone()) &&
                RxTool.Md5(getCode()).equals(smsCode.getCode())) {
            VerifyCodeManager.getInstance().cancel();
            ARouter.getInstance()
                    .build(ARouterConfig.WalletSetPwdPage1)
                    .withString("code", getCode())
                    .withBoolean("isChangePassword", true)// 是修改而不是初始化设置
                    .navigation();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChangeSuccessEventBuss(EventSetWalletPwdSuccess eventPasswordSuccess) {
        if (eventPasswordSuccess != null) {
            finish();
        }
    }

    private void sendVerifyCode() {
        if (sending) {
            return;
        }

        VerifyCodeManager.getInstance().tCaptchaDialog(this, new VerifyCodeManager.TCaptchaCallBack() {
            @Override
            public void success() {
                sending = true;
                ApiManager.getService().fetchByMobile(getPhone(), "walletPassword").enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) {
                        sending = false;
                        try {
                            if (response.isSuccessful()) {
                                smsCode = JsonUtil.toObject(response.body().string(), SmsCode.class);
                                VerifyCodeManager.getInstance().start();
                            } else {
                                ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                                onFailure(call, new Throwable(data.getMessage()));
                            }
                        } catch (Exception e) {
                            try {
                                onFailure(call, new Throwable(e.toString()));
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        sending = false;
                        if (t != null) {
                            ToastX.show(t.getMessage());
                        }
                    }
                });
            }

            @Override
            public void failed() {

            }
        });

    }

    private String getCode() {
        return etVerifyCode.getText().toString();
    }


    @OnClick({R.id.rl_back, R.id.tv_next, R.id.btn_send_verify_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_next:
                doNext();
                break;
            case R.id.btn_send_verify_code:
                sendVerifyCode();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        VerifyCodeManager.getInstance().removeLoginCallBack(this);
    }

    @Override
    public void onTick(long l) {
        //防止计时过程中重复点击
        btnSendVerifyCode.setEnabled(false);
        btnSendVerifyCode.setText((l / 1000) + "s");
        btnSendVerifyCode.setTextColor(ContextCompat.getColor(this, R.color.white));
    }

    @Override
    public void onFinish() {
        btnSendVerifyCode.setTextColor(ContextCompat.getColor(this, R.color.white));
        //重新给Button设置文字
        btnSendVerifyCode.setText(getResources().getString(R.string.get_verification_code));
        //设置可点击
        btnSendVerifyCode.setEnabled(true);
    }

}
